from email.mime.text import MIMEText
import smtplib
from email.header import Header
from functools import wraps
from datetime import datetime,timedelta

from config import get_config
from .create_summary import create_summary_html
from rich import print
from .row_utils import create_row

def sendemail(func):
    @wraps(func)
    def wrapper(*args,**kwargs):
        result = func(*args,**kwargs)
        do_send_email(result)
        return result
    return wrapper



def do_send_email(mlist):

    table_html = create_html_table(mlist)

    summary_html = create_summary_html(mlist)

    html = f"""
    <html>
      <body>
      {summary_html}
      {table_html}
     </body>
      </html>
    """

    try:
        conf = get_config()
        config = dict(conf)
        sender_email = config['sender_email']
        sender_email_code = config['sender_email_code']

        smtp_server = config['smtp_server']
        smtp_port = config['smtp_port']
        receiver_email = config['receiver_email']

        yesterday = datetime.now() - timedelta(days=1)
        yesterday_str = yesterday.strftime('%Y-%m-%d')
        subject = yesterday_str + '日志报告'

        msg = MIMEText(html, 'html', 'utf-8')  # 'plain' 表示纯文本，'utf-8' 编码
        msg['From'] = Header(sender_email)
        msg['To'] = Header(receiver_email)
        msg['Subject'] = Header(subject,'utf-8')

        server = smtplib.SMTP_SSL(smtp_server, int(smtp_port))
        server.login(sender_email, sender_email_code)  # 登录
        server.sendmail(sender_email,receiver_email,msg.as_string()) #发送邮件
        server.quit()
        print(f'[green]给{receiver_email}发送邮件成功')
    except KeyError as e:
        print(f'发送邮件失败，{e}')
    except Exception as e:
        print(f'发送邮件失败:{e}')
        raise e




def create_html_table(mlist):
    t_list = []
    for item in mlist:
        i_list = create_row(item)
        t_list.extend(i_list)
    body = ""
    for item in t_list:
        body = body +f"""
            <tr>
                <td>{item['file']}</td>
                <td>{item['reg']}</td>
                <td>{item['target']}</td>
            </tr>
        """

    table_body = f"""
          <table border="1" style="border-collapse: collapse; width: 100%;">
              <thead>
                  <tr style="background-color: #f2f2f2;">
                      <th>文件</th>
                      <th>匹配项</th>
                      <th>匹配值</th>
                  </tr>
              </thead>
              <tbody>
                    {body}
              </tbody>
          </table>
      """
    return table_body